package com.zz.common.service.IdService

import akka.actor.ActorSystem
import akka.http.javadsl.settings.ServerSettings
import akka.http.scaladsl.{Http, HttpConnectionContext}
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.stream.Materializer
import cats.implicits._
import cats.effect.{ContextShift, IO}
import com.zz.idl._

import scala.concurrent.{ExecutionContext, Future}

class ZidMappingService(zidService: Zidservice[IO]) extends com.zz.idl.IdMappingService {
  override def storeOrUpdate(in: IdBundle): Future[ZidWrapper] =
    zidService.storeOrUpdate(in).getOrElse("").map(ZidWrapper(_)).unsafeToFuture()

  override def storeOrUpdateInBatch(in: IdBundles): Future[Zids] =
    zidService.storeOrUpdateInBatch(in.idBundles).getOrElse(Vector.empty).map(Zids(_)).unsafeToFuture()

  override def getZid(in: QueryZid): Future[ZidWrapper] =
    zidService.queryZid(in.id, in.`type`).getOrElse("").map(ZidWrapper(_)).unsafeToFuture()
}

object ZidMappingService {
  def run(zidService: Zidservice[IO], host:String, port:Int)
         (implicit system: ActorSystem, mat: Materializer, ec: ExecutionContext): IO[Http.ServerBinding] = IO.fromFuture(IO{
    val service = IdMappingServiceHandler(new ZidMappingService(zidService))
    val binding = Http().bindAndHandleAsync(service, host, port)
    binding
  })(IO.contextShift(ec))
}
